import requests
import json
import cv2
import base64
import sys,os
from tkinter import * 
from tkinter import scrolledtext 
from tkinter import ttk, messagebox, filedialog

window = Tk()
menubar = Menu(window)
window.title("图片文字识别")
window.geometry("1200x700")

scr = scrolledtext.ScrolledText(window, width=80, height=15,font=("隶书",18))  #滚动文本框（宽，高（这里的高应该是以行数为单位），字体样式）
scr.place(x=50, y=50) #滚动文本框在页面的位置
scr.insert(END,"版本v0.0.2\n\n")   #将错题显示在动文本框中
# # 创建一个下拉菜单“文件”，然后将它添加到顶级菜单中
# selct_path = Menu(menubar, tearoff=False)
# selct_path.add_command(label = "打开", accelerator="Ctrl + O", command = lambda: open_dir(scr))
# menubar.add_cascade(label="文件", menu=selct_path)
# # 显示菜单
# window.config(menu=menubar)

# button1 = Button(window, text="打开文件", font=("隶书", 10), command=lambda: open_dir(scr))
# button1.place(x=300, y=550, width=150, height=60)
E1 = Entry(window, bd =1)
E1.place(x=210, y=615, width=100, height=30)



def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tobytes()).decode('utf8')
def send_img(scr=scr):
	ip = read_server_add()
	scr.insert(END,"图片识别中。。。。。\n\n")
	# 发送HTTP请求
	img_filename = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser("d://imgtofont")))
	scr.insert(END,img_filename+"\n\n")
	data = {'images':[cv2_to_base64(cv2.imread(img_filename))]}
	headers = {"Content-type": "application/json"}
	url = "http://%s/predict/chinese_ocr_db_crnn_server"%ip

	r = requests.post(url=url, headers=headers, data=json.dumps(data))
	listimg = r.json()["results"]
	# 打印预测结果
	for line in listimg:
		for linetext in line['data']:
			scr.insert(END,linetext['text']+"\n")

	scr.insert(END,"////////////////////////////\n")
	scr.insert(END,"图片识别完成！\n\n")

def add_server_addr(scr=scr,Ent=E1):
	# 打开一个文件
	ip = Ent.get()
	fo = open("server.txt", "w")
	fo.write("%s"%ip)
	# 关闭文件
	fo.close()
	scr.insert(END,"设置服务器地址:%s\n"%ip)   #将错题显示在动文本框中
def read_server_add(scr=scr):
	ip = ""
	try:
		fo = open("server.txt", "r")
		ip = fo.read()
	except:
		pass
	return ip

ipaddr = read_server_add()
if ipaddr:
	scr.insert(END,"服务器地址:%s\n"%ipaddr)
else:
	scr.insert(END,"请设置服务器地址\n")

button1 = Button(window, text="设置服务器地址", font=("隶书", 10), command=add_server_addr)
button1.place(x=50, y=600, width=150, height=60)
button2 = Button(window, text="开始识别", font=("隶书", 10), command=send_img)
button2.place(x=500, y=600, width=150, height=60)
button3 = Button(window, text="退	出", font=("隶书", 10), command=sys.exit)
button3.place(x=700, y=600, width=150, height=60)
window.mainloop()
exit()